<?php
namespace app\middleware;

use app\controller\Base;
use tinywan\JWT;

use think\facade\Db;
/**
 * 权限判断中间件
 * Description: 用于控制接口权限
 */

class CheckAuth extends Base
{
    /**
     * 检测登录中间件
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $response = $next($request);
        try {
            $user = Jwt::getExtend();
            $group_id = Db::table('admin_member')->where('id',$user['id'])->value('group_id');
            if(!empty($group_id)){
                if($group_id === 1){
                    // 管理员组直接放行
                    return $response;
                }else{
                    // 当前访问的控制器与方法
                    $access_path = '/' . Request()->controller() . '/' . Request()->action();
                    // 这个用户的所有权限值
                    $ids_data = Db::table('admin_department')->where('id',$group_id)->value('permission_ids');
                    if(!$ids_data)return $this->createMsg([],'您没有权限!',400);
                    // 权限值字符串转化为数组
                    $ids = explode(',', $ids_data);
                    // 获取当前访问路径的权限ID
                    $path_id = Db::table('admin_permission')->where('permission_link',$access_path)->value('id');
                    if (!in_array($path_id, $ids)) {
                        // 不在权限数组中
                        return $this->createMsg([],'您需要授权!',400);
                    }
                }
            }else{
                return $this->createMsg([],'您尚未有此功能权限!',400);
            }
        }catch (\Exception $e){
            return $this->createMsg([],$e->getMessage(),400);
        }

        return $response;
    }
}